﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using CDI.IndexCard3D;
using DevExpress.XtraBars;
using Lpfm.LastFmScrobbler;
using Lpfm.LastFmScrobbler.Api;
using Microsoft.Win32;
using WMPLib;
using WMPLibAlias = WMPLib;
using ComponentOwl.BetterListView;

namespace JipPlayer_2._0
{

    public partial class frmMainDX : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        #region Declaring All Global Variables

        private QueuingScrobbler _scrobbler;
        private const string ApiKey = "2f6c7254dd29a1437941dac20fe84ba4";
        private const string ApiSecret = "1a67298a4f011b730389cd3b5e725c27";
        readonly WindowsMediaPlayer Muziek = new WindowsMediaPlayer();
        readonly ListBox URLFiles = new ListBox();
        TagLib.File ID3;
        TimeSpan trackTimeConvertor;
        ProcessScrobblesDelegate doProcessScrobbles;
        readonly Track CurrentTrack = new Track();
        private delegate void ProcessScrobblesDelegate();
        private void ProcessScrobbles()
        {
            // Processes the scrobbles and discards any responses. This could be improved with thread-safe
            //  logging and/or error handling
            _scrobbler.Process();
        }        
        bool useNowPlaying, useLastFM, scrobble, shuffle;
        StreamWriter musicIndex;
        RegistryKey getSessionKey = Registry.CurrentUser.OpenSubKey("Software\\JipPlayer 2.0", true);
        int nextInShuffleArray;
        string itemstoarray;
        string[] shuffleArray;
        public string ID3URL;
        #endregion

        #region Memory footprint reducer DLL import

        [DllImport("psapi.dll")]
        static extern int EmptyWorkingSet(IntPtr hwProc);

        static void MinimizeFootprint()
        {
            EmptyWorkingSet(Process.GetCurrentProcess().Handle);
        }

        #endregion

        #region Form Load
        
        public frmMainDX()
        {
            InitializeComponent();            
        }

        private void frmMainDX_Load(object sender, EventArgs e)
        {
            Text = "JipPlayer " + Application.ProductVersion;
            ReadIndex();

            if (getSessionKey == null)
            {
                Registry.CurrentUser.CreateSubKey("Software\\JipPlayer 2.0");
            }
            if (getSessionKey.GetValue("useNowPlaying", "False").ToString() == "True")
            {
                useNowPlaying = true;
            }
            else
            {
                useNowPlaying = false;
            }
            if (getSessionKey.GetValue("useLastFM", "False").ToString() == "True")
            {
                useLastFM = true;
                string sessionKey = GetSessionKey();
                // instantiate the async scrobbler
                _scrobbler = new QueuingScrobbler(ApiKey, ApiSecret, sessionKey);
            }
            else
            {
                useLastFM = false;
            }
            if (getSessionKey.GetValue("shuffle", "False").ToString() == "True")
            {
                shuffle = true;
                CreateShuffleList();
                nextInShuffleArray = URLFiles.Items.Count;
                btnShuffle.Image = Properties.Resources.shuffleused;
            }
            else
            {
                shuffle = false;
            }

            MinimizeFootprint();
        }      

        #endregion

        #region Menu Items
       
        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }

        private void openFile_ItemClick(object sender, ItemClickEventArgs e)
        {
            string url;
            if (OpenenDialog.ShowDialog() == DialogResult.OK)
            {
                //  ID3 Reader
                url = OpenenDialog.FileName;
                if ((url.EndsWith(".wav") || url.EndsWith(".mp3")))
                {
                    try
                    {
                        GetID3AndAddFile(url);
                    }
                    catch
                    {
                        MessageBox.Show((url + " is not a valid mp3 file or has invalid tag information"));
                        return;
                    }

                    //now playing label aangepast
                    try
                    {
                        labelPlaying.Text = String.Format("Now Playing: {0} from {1}", (ImportedFiles.SelectedItems[0].Index + 1), ImportedFiles.Items.Count);
                    }
                    catch
                    {
                        labelPlaying.Text = "Now Playing: 0 from " + ImportedFiles.Items.Count;
                    }

                }
            }
        }

        private void barButtonItem2_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (musicImport.ShowDialog() == DialogResult.OK)
            {
                ImportedFiles.Items.Clear();
                URLFiles.Items.Clear();
                musicIndex = new StreamWriter(Application.StartupPath + @"\MusicIndex.dat");
                ProcessDir(musicImport.SelectedPath, 0);
                musicIndex.Close();
            }
        }

        private void OptionClose_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (frmSettingsDX frmSettingsDX = new frmSettingsDX())
            {
                frmSettingsDX.ShowDialog();
            }

            if (getSessionKey.GetValue("useNowPlaying", "False").ToString() == "True")
            {
                useNowPlaying = true;
            }
            else
            {
                useNowPlaying = false;
            }
            if (getSessionKey.GetValue("useLastFM", "False").ToString() == "True")
            {
                useLastFM = true;
                string sessionKey = GetSessionKey();
                // instantiate the async scrobbler
                _scrobbler = new QueuingScrobbler(ApiKey, ApiSecret, sessionKey);
            }
            else
            {
                useLastFM = false;
            }
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            URLFiles.Items.Clear();
            ImportedFiles.Items.Clear();
            musicIndex = new StreamWriter(Application.StartupPath + @"\MusicIndex.dat");
            musicIndex.Close();
            if (Muziek.playState == WMPLibAlias.WMPPlayState.wmppsPlaying)
            {
                labelPlaying.Text = "Now Playing: 1 from 0";
            }
            else
            {
                labelPlaying.Text = "Now Playing: 0 from 0";
            }
        }

        #endregion

        #region partial Classes
        
        public void ProcessDir(string sourceDir, int recursionLvl)
        {
            {
                // Process the list of files found in the directory. 
                string[] fileEntries = Directory.GetFiles(sourceDir);
                foreach (string fileName in fileEntries)
                {
                    if (fileName.EndsWith(".mp3") || fileName.EndsWith(".wav"))
                    {
                        musicIndex.WriteLine(fileName);
                        try
                        {
                            GetID3AndAddFile(fileName);
                        }
                        catch
                        {
                            MessageBox.Show((fileName + " is not a valid mp3 file or has invalid tag information"));
                            return;
                        }
                    }
                }

                // Recurse into subdirectories of this directory.
                string[] subdirEntries = Directory.GetDirectories(sourceDir);
                foreach (string subdir in subdirEntries)
                    // Do not iterate through reparse points
                    if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
                    {
                        ProcessDir(subdir, recursionLvl + 1);
                    }
            }

        }

        private void GetID3AndAddFile(string url)
        {            
            //  ID3 Reader            
            if ((url.EndsWith(".wav") | url.EndsWith(".mp3")))
            {
                
                try
                {
                    ID3 = TagLib.File.Create(url);
                    string[] str = new string[7]; 
   
                    /*
                    ImageList imgList = new ImageList();
                    ImportedFiles.ImageList = imgList;
                    imgList.Images.Add("image", );
                    BetterListViewItem itm = new BetterListViewItem("", imgList.Images.IndexOfKey("image"));                    
                    ImportedFiles.Items.Add(itm);
                    */

                    //  str 0 = Track title
                    //  str 1 = Album
                    //  str 2 = Artist
                    //  str 3 = genre
                    //  str 4 = year
                    if (ID3.Tag.Title == "")
                    {
                        str[0] = Path.GetFileNameWithoutExtension(url);
                    }
                    else
                    {
                        str[0] = String.Empty;
                        str[1] = ID3.Tag.Title;
                        str[2] = ID3.Tag.Album;
                        str[3] = ID3.Tag.FirstPerformer;
                        str[4] = ID3.Tag.FirstGenre;
                        str[5] = ID3.Tag.Year.ToString();
                        str[6] = ID3.Tag.Track.ToString();                        
                    }
                    URLFiles.Items.Add(url);
                    BetterListViewItem itm = new BetterListViewItem(str);
                    ImportedFiles.Items.Add(itm);
                    if (File.Exists(Path.GetDirectoryName(url) + @"\Folder.jpg"))
                    {
                        System.Drawing.Image tempImage = System.Drawing.Image.FromFile(Path.GetDirectoryName(url) + @"\Folder.jpg");
                        tempImage = tempImage.GetThumbnailImage(128, 128, null, IntPtr.Zero);
                        ImportedFiles.Items[ImportedFiles.Items.Count - 1].SubItems[0].Image = tempImage;
                    }
            }    
                    catch (Exception e)
                        {
                            MessageBox.Show(e.ToString());
                        //MessageBox.Show((url + " is not a valid mp3 file or has invalid tag information"));
                        return;
                        }
            }
            nextInShuffleArray = URLFiles.Items.Count;
        }

        private void NewSong()
        {
            if (ImportedFiles.SelectedItems.Count != 0)
            {

                URLFiles.SelectedIndex = ImportedFiles.SelectedIndices[0];

                if (useNowPlaying)
                {
                    foreach (Process clsProcess in Process.GetProcesses())
                    {
                        if (clsProcess.ProcessName.Contains("msnmsgr"))
                        {
                            WLMStatus(ImportedFiles.SelectedItems[0].SubItems[0].Text, ImportedFiles.SelectedItems[0].SubItems[2].Text);
                        }
                    }
                }
                else
                {
                    foreach (Process clsProcess in Process.GetProcesses())
                    {
                        if (clsProcess.ProcessName.Contains("msnmsgr"))
                        {
                            WLMStatusChanger.SendMSNMessage(false, WLMStatusChanger.MessageCategory.Music, "", "");
                        }
                    }
                }


                // Show Albumart
                if (File.Exists(Path.GetDirectoryName(URLFiles.SelectedItem.ToString()) + @"\Folder.jpg"))
                {

                    albumArt.ImageLocation = Path.GetDirectoryName(URLFiles.SelectedItem.ToString()) + @"\Folder.jpg";


                    Card c = default(Card);
                    Bitmap b = new Bitmap(Path.GetDirectoryName(URLFiles.SelectedItem.ToString()) + @"\Folder.jpg");
                    Font fnt = new Font("Verdana", 80, FontStyle.Bold, GraphicsUnit.Pixel);

                    /*
                    b = new Bitmap(255, 255);
                    g = Graphics.FromImage(b);
                    g.Clear(Color.FromArgb(100, 50, 50, 50));
                    g.DrawString(ImportedFiles.SelectedItems[0].SubItems[0].Text, fnt, Brushes.GhostWhite, 40, 70);
                    */

                    //Add the new bitmap and directory/drive information to our index card object
                    c = new Card(string.Concat("Album ", ImportedFiles.SelectedItems[0].Index + 1), b);
                    flowGallery.IndexCards.Add(c);
                    //Add the index card to our index cards collection

                    //////////g.Dispose();
                    //clean up
                    flowGallery.IndexCards.LoadTexturesToMemory();
                }
                
                // show in label current playing song
                labelPlaying.Text = String.Format("Now Playing: {0} from {1}", (ImportedFiles.SelectedItems[0].Index + 1), ImportedFiles.Items.Count);
                // Enabled TrackBar Timer
                musicTrackbar.Value = 0;
                timerTrackbar.Enabled = true;
                Muziek.URL = URLFiles.SelectedItem.ToString();
                scrobble = true;
            }
        }

        private static void WLMStatus(string liedje, string artiest)
        {
            WLMStatusChanger.SendMSNMessage(true, WLMStatusChanger.MessageCategory.Music, liedje, artiest);
        }

        private string GetSessionKey()
        {
            // try get the session key from the registry

            string sessionKey = (string)getSessionKey.GetValue("sessionKey", "", RegistryValueOptions.None);
            if (string.IsNullOrEmpty(sessionKey))
            {
                // instantiate a new scrobbler
                var scrobbler = new Scrobbler("2f6c7254dd29a1437941dac20fe84ba4", "1a67298a4f011b730389cd3b5e725c27");

                //NOTE: This is demo code. You would not normally do this in a production application
                while (string.IsNullOrEmpty(sessionKey))
                {
                    // Try get session key from Last.fm
                    try
                    {
                        sessionKey = scrobbler.GetSession();
                        RegistryKey JipPlayerKey = Registry.CurrentUser.CreateSubKey("Software\\JipPlayer 2.0");
                        JipPlayerKey = Registry.CurrentUser.OpenSubKey("Software\\JipPlayer 2.0", true);
                        JipPlayerKey.SetValue("sessionKey", sessionKey, RegistryValueKind.String);
                        // successfully got a key. Save it to the registry for next time
                        //SetRegistrySetting(sessionKeyRegistryKeyName, sessionKey);
                    }
                    catch (LastFmApiException exception)
                    {
                        // get session key from Last.fm failed
                        MessageBox.Show(exception.Message);

                        // get a url to authenticate this application
                        string url = scrobbler.GetAuthorisationUri();

                        // open the URL in the default browser
                        System.Diagnostics.Process.Start(url);

                        // Block this application while the user authenticates
                        MessageBox.Show("Click OK when Application authenticated");
                    }
                }
            }

            return sessionKey;
        }

        private void ReadIndex()
        {
            ImportedFiles.BeginUpdate();
            if (File.Exists(Application.StartupPath + @"\MusicIndex.dat"))
            {
                using (StreamReader importMusicFromIndex = new StreamReader(Application.StartupPath + @"\MusicIndex.dat"))
                {
                    do
                    {
                        GetID3AndAddFile(importMusicFromIndex.ReadLine());
                    }
                    while (importMusicFromIndex.EndOfStream != true);
                    importMusicFromIndex.Close();
                }
            }
            ImportedFiles.EndUpdate();
        }

        private void CreateShuffleList()
        {
            itemstoarray = null;
            shuffleArray = null;
            int items = URLFiles.Items.Count;
            do
            {
                itemstoarray = String.Format("{0}{1},", itemstoarray, items);
                items -= 1;
            }
            while (items != 0);
            itemstoarray = itemstoarray.Remove(itemstoarray.Length - 1, 1);
            shuffleArray = itemstoarray.Split(",".ToCharArray());
            new Random().Shuffle(shuffleArray);
            nextInShuffleArray = URLFiles.Items.Count;
            MinimizeFootprint();
        }

        #endregion

        private void ImportedFiles_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            BetterListViewHitTestInfo hit = ImportedFiles.HitTest(e.Location);
            if ((hit.Locations & BetterListViewHitTestLocations.ContentArea) == BetterListViewHitTestLocations.ContentArea)
            {
                if (useLastFM)
                {
                    try
                    {
                        _scrobbler.Scrobble(CurrentTrack);
                        doProcessScrobbles.BeginInvoke(null, null);
                    }
                    catch
                    {
                        // Do Nothing
                    }
                }

                NewSong();
                btnPlayPause.Image = Properties.Resources.Pause_64;
            }
        }

        private void frmMainDX_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (useLastFM)
            {
                try
                {
                    _scrobbler.Scrobble(CurrentTrack);
                    doProcessScrobbles.BeginInvoke(null, null);
                }
                catch 
                {
                    //niks, als er niks speelt niet erg...
                }
            }
            Application.DoEvents();
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains("msnmsgr"))
                {
                    WLMStatusChanger.SendMSNMessage(false, WLMStatusChanger.MessageCategory.Music, "", "");
                }
            }
        }

        private void timerTrackbar_Tick(object sender, EventArgs e)
        {
            if (scrobble == true & useLastFM)
            {
                // Last.FM Scrobbler
                try
                {
                    doProcessScrobbles = ProcessScrobbles;

                    // Convert the media player media info to a Track. Store the track in a property so that is can be scrobbled 
                    //  when media ended. At that time WindowsMediaPlayer.currentMedia will be null. This is not fool-proof and
                    //  is demo code only
                    TimeSpan duration = new TimeSpan(0, 0, 0, (int)musicTrackbar.Maximum);
                    CurrentTrack.Duration = duration;
                    CurrentTrack.ArtistName = ImportedFiles.SelectedItems[0].SubItems[2].Text;
                    CurrentTrack.TrackName = ImportedFiles.SelectedItems[0].SubItems[0].Text;
                    CurrentTrack.TrackNumber = Convert.ToInt32(ImportedFiles.SelectedItems[0].SubItems[5].Text);
                    CurrentTrack.WhenStartedPlaying = DateTime.Now;

                    // we are using the Queuing scrobbler here so that we don't block the form while the scrobble request is being sent
                    //  to the Last.fm web service. The request will be sent when the Process() method is invoked
                    _scrobbler.NowPlaying(CurrentTrack);
                    // Begin invoke with no callback fires and forgets the scrobbler process. Processing runs asynchronously while 
                    //  the form thread continues
                    doProcessScrobbles.BeginInvoke(null, null);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                scrobble = false;
            }

            musicTrackbar.Maximum = Convert.ToInt32(Muziek.currentMedia.duration);

            if (musicTrackbar.Value == musicTrackbar.Maximum)
            {
                if (shuffle == true)
                {
                    if (nextInShuffleArray == 0)
                    {
                        CreateShuffleList();
                    }
                    else
                    {
                        nextInShuffleArray -= 1;
                        ImportedFiles.Items[Convert.ToInt32(shuffleArray.GetValue(nextInShuffleArray)) - 1].Selected = true;
                        ImportedFiles.Select();                        
                    }
                }
                else
                {
                    if ((URLFiles.SelectedIndices[0] + 1) == ImportedFiles.Items.Count)
                    {
                        ImportedFiles.Items[0].Selected = true;
                        ImportedFiles.Select();
                    }
                    else
                    {
                        ImportedFiles.Items[URLFiles.SelectedIndices[0] + 1].Selected = true;
                        ImportedFiles.Select();
                    }
                }
                //Application.DoEvents();
                if (useLastFM)
                {
                    _scrobbler.Scrobble(CurrentTrack);
                    doProcessScrobbles.BeginInvoke(null, null);
                }
                //Application.DoEvents();
                timerTrackbar.Enabled = false;
                NewSong();
            }
            else
            {
                musicTrackbar.Value = Convert.ToInt32(Muziek.controls.currentPosition);
                trackTimeConvertor = TimeSpan.FromSeconds(Convert.ToInt32(Muziek.controls.currentPosition));
                trackTime.Text = trackTimeConvertor.ToString();
            }
            
        }

        #region Trackbars

        private void musicTrackbar_Scroll(object sender, EventArgs e)
        {
            Muziek.controls.currentPosition = musicTrackbar.Value;
        }

        private void macTrackBar1_Scroll(object sender, EventArgs e)
        {
            Muziek.settings.volume = volumeTrackbar.Value;
        }

        #endregion

        #region Play Control Buttons

        private void btnPlayPause_Click_1(object sender, EventArgs e)
        {
            if (Muziek.playState == WMPLibAlias.WMPPlayState.wmppsPlaying)
            {
                Muziek.controls.pause();

            }
            else if (Muziek.playState == WMPLibAlias.WMPPlayState.wmppsPaused)
            {
                Muziek.controls.play();
            }
        }

        private void btnNextSong_Click_1(object sender, EventArgs e)
        {
            if (ImportedFiles.SelectedItems.Count > 0)
            {
                if (shuffle == true)
                {
                    if (nextInShuffleArray <= 0)
                    {
                        CreateShuffleList();
                    }
                    else
                    {
                        nextInShuffleArray -= 1;
                        ImportedFiles.Items[Convert.ToInt32(shuffleArray.GetValue(nextInShuffleArray)) - 1].Selected = true;
                        ImportedFiles.Select();
                    }
                }
                else
                {
                    if ((ImportedFiles.SelectedIndices[0] + 1) == ImportedFiles.Items.Count)
                    {
                        ImportedFiles.Items[0].Selected = true;
                        ImportedFiles.Select();
                    }
                    else
                    {
                        ImportedFiles.Items[ImportedFiles.SelectedIndices[0] + 1].Selected = true;
                        ImportedFiles.Select();
                    }
                }
                timerTrackbar.Enabled = false;
                NewSong();
            }
        }

        private void btnPreviousSong_Click_1(object sender, EventArgs e)
        {
            if (ImportedFiles.SelectedItems.Count > 0)
            {
                if (shuffle == true)
                {
                    if (nextInShuffleArray <= 0)
                    {
                        CreateShuffleList();
                    }
                    else
                    {
                        nextInShuffleArray -= 1;
                        ImportedFiles.Items[Convert.ToInt32(shuffleArray.GetValue(nextInShuffleArray)) - 1].Selected = true;
                        ImportedFiles.Select();
                    }
                    
                }
                else
                {
                    if ((ImportedFiles.SelectedIndices[0]) == 0)
                    {
                        ImportedFiles.Items[ImportedFiles.Items.Count - 1].Selected = true;
                        ImportedFiles.Select();
                    }
                    else
                    {
                        ImportedFiles.Items[ImportedFiles.SelectedIndices[0] - 1].Selected = true;
                        ImportedFiles.Select();
                    }
                }
                timerTrackbar.Enabled = false;
                NewSong();
            }
        }

        #region Images change when pressed and release

        private void btnPlayPause_MouseDown(object sender, MouseEventArgs e)
        {
            if (Muziek.playState == WMPPlayState.wmppsPaused)
            {
                btnPlayPause.Image = Properties.Resources.Play_64_pressed;
            }
            else
            {
                btnPlayPause.Image = Properties.Resources.Pause_64_pressed;
            }
        }

        private void btnPlayPause_MouseUp(object sender, MouseEventArgs e)
        {
            if (Muziek.playState == WMPPlayState.wmppsPlaying)
            {
                btnPlayPause.Image = Properties.Resources.Pause_64;
            }
            else
            {
                btnPlayPause.Image = Properties.Resources.Play_64;
            }
        }

        private void btnNextSong_MouseDown(object sender, MouseEventArgs e)
        {
            btnNextSong.Image = Properties.Resources.Next_track_64_pressed;
        }

        private void btnNextSong_MouseUp(object sender, MouseEventArgs e)
        {
            btnNextSong.Image = Properties.Resources.Next_track_64;
        }

        private void btnPreviousSong_MouseDown(object sender, MouseEventArgs e)
        {
            btnPreviousSong.Image = Properties.Resources.Previous_track_64_pressed;
        }

        private void btnPreviousSong_MouseUp(object sender, MouseEventArgs e)
        {
            btnPreviousSong.Image = Properties.Resources.Previous_track_64;
        }

        #endregion

        private void btnShuffle_Click(object sender, EventArgs e)
        {
            if (shuffle == true)
            {
                shuffle = false;
                getSessionKey.SetValue("shuffle", "False");
                btnShuffle.Image = Properties.Resources.shuffle;
            }
            else
            {
                shuffle = true;
                getSessionKey.SetValue("shuffle", "True");
                btnShuffle.Image = Properties.Resources.shuffleused;
                CreateShuffleList();
            }
        }        

        #endregion               

        private static void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmAbout frmAbout = new frmAbout())
            {
                frmAbout.ShowDialog();
            }
        }                 

        private void btnAbout_Click(object sender, EventArgs e)
        {
            frmAbout about = new frmAbout();
            about.Show();
        }   

        private void txtSearch_EditValueChanged(object sender, EventArgs e)
        {
            ImportedFiles.BeginUpdate();
            if (txtSearch.Text == "")
            {
                ImportedFiles.Items.Clear();
                URLFiles.Items.Clear();
                ReadIndex();                
            }
            else
            {
                foreach (ComponentOwl.BetterListView.BetterListViewItem check in ImportedFiles.Items)
                {
                    if (check.Text.ToLower().Contains(txtSearch.Text.ToLower()) == false)
                    {
                        URLFiles.Items.RemoveAt(check.Index);
                        check.Remove();
                    }
                }
            }
            ImportedFiles.EndUpdate();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Muziek.controls.stop();
            Muziek.close();
            Muziek.URL = "";
            Application.DoEvents();
            frmID3TagEditor Edit = new frmID3TagEditor();
            URLFiles.SelectedIndex = ImportedFiles.SelectedIndices[0];
            Edit.url = URLFiles.SelectedItem.ToString();
            Edit.Show();
        }

    }
}